<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
ini_set('max_execution_time', '0');

/*******************
***  处理外部123数据库数据FBA数据
***  http://192.168.1.100:89/fshop/
*** 2017/05/10
**********/
class AmazondataFBA
{

	 public function __construct()
    {
        $this->CI =& get_instance();
        $this->db1 = $this->CI->load->database('default', TRUE);
        $this->db2 = $this->CI->load->database('amazondata', TRUE);
		$this->CI->load->model('Function_m','fun');
    }
	

	/*************读取123数据库newamazondb表中的数据到订单列表*********************/
	/********flag = 1 and ordersource = MFN *************/
	public function getinsertorderlist()
	{
	
		$factorycode = $this->factorycode();
		
		$this->db2->limit(1);
		$row = $this->db2->get_where("db_amzordertmp","flag=1 AND fulfillmentchannel = 'AFN' AND status='已发货' ")->result_array();
		//$row = $this->db2->get_where("db_amzordertmp"," tradeid='112-3906776-8833809' AND fulfillmentchannel = 'AFN' AND status='已发货'")->result_array();

		
		if(count($row)==0)
		{
			return false;
		}
		$rs = $row[0];
		
	
			$rorder = $this->db1->get_where("db_amzordertmp","tradeid='".$rs["tradeid"]."'")->result_array();
			if($rorder[0]["id"])
			{
				$this->db2->update("db_amzordertmp",array("flag"=>2,"descr"=>'早已同步系统成功'),"tradeid='".$rs["tradeid"]."' ");
				return $this->getinsertorderlist();
			}
			
			$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["moneytype"]."'")->result_array();
			$exchangerate=$exchange[0]["rate"]; 
			$postdata="";
			$randCode = $this->randCode(5,1);
			$postdata["groupid"] =  $this->getNo('amazon',$rs["tradeid"],$rs["shopid"]);
			$orts=strtotime($rs['lastupdatetime']);
			$dates = date("Y-m-d",$orts);
			//$postdata["dates"] = $dates;

			//$postdata["dates"] = date("Y-m-d");
			if($rs["shopname"] =='givevcos')
			{
				$postdata["dates"] = $dates;
			}else{
				$postdata["dates"] = date("Y-m-d",$rs['instime']);
			}
				
			
			
			$postdata["custid"] =addslashes(trim($rs["custid"]));
			$postdata["custname"] =addslashes(trim($rs["custname"]));
			if($rs["custcountry"]){
				$postdata["custcountry"] = $rs["custcountry"];
				$rscountry = $this->db1->get_where("d_country","countrynamecn='".$rs["custcountry"]."'")->result_array();
				if($rscountry[0]["id"]){
					$postdata["country_cn"] = $rscountry[0]["countrynameen"];
				}
			}else{
				if($rs["countrycode"])
				{
					$rscountry = $this->db1->get_where("d_country","countryid='".trim($rs["countrycode"])."'")->result_array();
					$postdata["custcountry"] = strtolower($rscountry[0]['countrynamecn']);
					$postdata["country_cn"] = $rscountry[0]["countrynameen"];
				}
			}
			if($rs["countrycode"]=="")
			{
				$rscountry = $this->db1->get_where("d_country","countrynamecn='".trim($rs["custcountry"])."'")->result_array();
				$country_code = $rscountry[0]['countryid'];
			}else{
				$country_code = $rs["countrycode"];
			}
			$postdata["countrycode"] = $country_code;

			$postdata["custprovince"] = $rs["custprovince"];
			$postdata["custcity"] = $rs["custcity"];
			$postdata["custaddress1"] = addslashes(trim($rs["custaddress1"]));
			$postdata["custaddress2"] = addslashes(trim($rs["custaddress2"]));
			$postdata["custzipcode"] = $rs["custzipcode"]?$rs["custzipcode"]:0;
			$postdata["custtel1"] = $rs["custtel1"]?$rs["custtel1"]:0;
			$postdata["custtel2"] = $rs["custtel2"];
			$postdata["custemail"] = $rs["custemail"];

			$rshop = $this->db1->get_where("d_shop","name='".$rs["shopname"]."'")->result_array();
			$postdata["shopname"] = $rshop[0]["name"];
			$postdata["shopid"] = $rshop[0]["id"];


			$postdata["moneytype"] = $rs["moneytype"];
			$postdata["tradeid"] = $rs["tradeid"];
			$postdata["fulfillmentchannel"] = 'AFN';
			$postdata["status"] = 1;
			$postdata["origintotle"] = $rs["origintotle"];
			$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["moneytype"]."'")->result_array();
			$exchangerate=$exchange[0]["rate"]; 
			$orderask = $rs["origintotle"] * $exchangerate;
			$postdata["goods_amount"] =$orderask;
			$postdata["shipping_fee"] = $rs["originexpressask"]* $exchangerate;	//遇到运费有折扣的需要去除
			$postdata["originexpressask"] = $rs["originexpressask"];
			$postdata["instime"] = time();
			$postdata["ordercreatetime"] = $rs["ordercreatetime"];
			$postdata["saleschannel"] = $rs["saleschannel"];
			
			$originexpressask = $rs["originexpressask"]* $exchangerate;

			if($rshop[0]["shop_platform_fee"]>0)
			{
				$shop_platform_fee  =$rshop[0]["shop_platform_fee"];
			}else{
				$shop_platform_fee = 0.15;
			}
			if($rshop[0]["shop_pay_fee"]>0)
			{
				$shop_pay_fee  =$rshop[0]["shop_pay_fee"];
			}else{
				$shop_pay_fee = 0.015;
			}
			

			$postdata["pay_fee"] =($orderask+$originexpressask)*$shop_pay_fee;
			$postdata["platform_fee"] =($orderask+$originexpressask)*$shop_platform_fee;
			$postdata['moneyrate']  = $exchangerate;//汇率
		
			$this->db1->trans_begin();	//事务开始
			
				$this->db1->insert("db_amzordertmp",$postdata);
				$orderID = $this->db1->insert_id();
				
				



				$sell = $this->db2->get_where("db_amzordertmpsell","ordertmpid='".$rs["id"]."'")->result_array();
				
				$weight = 0;
				$allshipprice=0;
				$origintotle = 0;
				foreach($sell as $key=>$res)
				{
					
				

					$allshipprice =$allshipprice+$res['shipprice']-$res['codfeediscount'];	//运费.需要减去折扣
					$origintotle = $origintotle+$res['sellprice']*$res["ordernum"];	//商品金额
					$oldgoodsku = $res["productid"];
					if(strpos($oldgoodsku,"@") === false){  
						$oldgoodsku = $res["productid"];
					}else{
						$oldgoodsku = explode("@",$res["productid"]);
						$oldgoodsku = $oldgoodsku[0];
					}

						$oldgoodsku = str_replace("-FBA","",$oldgoodsku);
						$oldgoodsku = str_replace("-fba","",$oldgoodsku);
						$oldgoodsku = str_replace("FBA-","",$oldgoodsku);
						$oldgoodsku = str_replace("FBA","",$oldgoodsku);
						$oldgoodsku = trim($oldgoodsku);

					/*****************替换SKU方式********
						**  1、是否存在123.fshop数据库d_aotocreatesku表中
						**  2、是否存在在商品的db_goods 中的cognatelist字段
						**  3、是否db_salesku中
					*********************************/
					$productid = "";
					$newgoods = $this->db2->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopname='".$rshop[0]["name"]."' ")->result_array();
					if(count($newgoods)>0)
					{
						$productid = $newgoods[0]["parentsku"];
						$newgoods = $this->db1->get_where("db_goods","goods_sku='".$productid."' or cognatelist like '%,".$productid.",%' ")->result_array(); //找SKU是否存在
						if(count($newgoods)>0)
						{
							$productid = $newgoods[0]["goods_sku"];
						}
					}else{
						$newgoods = $this->db1->get_where("db_goods","goods_sku='".$oldgoodsku."' or cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
						if(count($newgoods)>0)
						{
							$productid = $newgoods[0]["goods_sku"];
						}else{
							$newgoods = $this->db1->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();
							if(count($newgoods)>0)
							{
								$productid = $newgoods[0]["goods_sku"];
							}
						
						}
					}

					if(!$productid)
					{
						$productid = $oldgoodsku;
					}

					





					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$productid."'")->result_array();
					if($rgoods[0]["goods_id"])
					{
						$goods_id = $rgoods[0]["goods_id"];
						$sweight = $res["ordernum"] * $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						$goods_name =  $rgoods[0]["goods_name"];
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						$costprice = 0;
						if(is_numeric($productid) && preg_match('|^\d{8}$|',$productid))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($productid,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
							
						}
						
					}else{
						$goods_id = 0 ;
						$costprice = 0;
						$goods_name="";
					}

					$amount = $res["ordernum"] * $res["sellprice"];
					$postsell = "";
					$postsell["ordertmpid"] = $orderID;
					$postsell["productname"] = $goods_name?$goods_name:addslashes($res["productname"]);
					$postsell["productid"] = $productid;
					$postsell["goods_id"] = $goods_id;
					$postsell["costprice"] = $costprice*$res["ordernum"];
					$postsell["ordernum"] = $res["ordernum"];
					$postsell["sellprice"] = $res["sellprice"]*$exchangerate;
					$postsell["goods_weight"] = $rgoods[0]["g_weight"]?$rgoods[0]["g_weight"]:0;
					$postsell["goods_amount"] = $amount*$exchangerate;
					$postsell["originsellprice"] = $res["sellprice"];
					$postsell["oldgoodsku"] = $oldgoodsku;

					$postsell["transactionid"] =$res["transactionid"];
					$postsell["codefee"] =$res["codefee"];;
					$postsell["codfeediscount"] =$res["codfeediscount"];
					$postsell["amount"] =$res["amount"];
					$postsell["asin"] =$res["asin"];
					$postsell["promotionDiscount"] =$res["promotionDiscount"];

					//当前头程费用
					$derprice = $this->CI->fun->get_oversea_express_costprice(trim($productid),$rshop[0]["name"]);

					if($derprice>0){
						$postsell["deliverprice"] =$derprice;
					}else{
						$postsell["deliverprice"] =0;
					}


					$this->db1->insert("db_amzordertmpsell",$postsell);
					if($goods_id==0)
					{
						$this->db1->update("db_amzordertmp",array("status"=>2),"id=".$orderID);
					}else{
						$cotnet = $rs["tradeid"]."-FBA订单";
						$this->CI->fun->goods_stock_log($orderID,$goods_id,$rshop[0]["id"],$cotnet,$res["ordernum"],0,$res["ordernum"],0,'SYS',1); 
					}


				}
				
				$rowcost = $this->db2->get_where("db_fba_cost"," amazon_id = '".$rs["tradeid"]."'")->result_array();	//读取FBA的费用
				if(count($rowcost)>0)
				{
					$rowcose = $rowcost[0];
					if($rowcose['totalFBAcost'] !=0)
					{
						$fees = $rowcose['totalFBAcost'];
					}else{
						$fees = $rowcose['FBAPerOrderFulfillmentFee'] + $rowcose['FBAPerUnitFulfillmentFee'] + $rowcose['FBAWeightBasedFee'] + $rowcose['Commission'] + $rowcose['FixedClosingFee'] + $rowcose['GiftwrapChargeback'] + $rowcose['SalesTaxCollectionFee'] + $rowcose['ShippingChargeback'] + $rowcose['VariableClosingFee'];
					}
					$payship_fee = $fees *$exchangerate;
					$this->db1->update("db_amzordertmp",array("payship_fee"=>$payship_fee),"id=".$orderID);
				}

				if($allshipprice)
				{
					$shipping_fee =round($allshipprice * $exchangerate,2);
					$this->db1->update("db_amzordertmp",array("originexpressask"=>$allshipprice,"shipping_fee"=>$shipping_fee),"id=".$orderID);
				}
				if($origintotle)
				{
					$orderask = round($origintotle * $exchangerate,2);
					$pay_fee = round($orderask*$shop_pay_fee,2);
					$platform_fee = round($orderask*$shop_platform_fee,2);
					$this->db1->update("db_amzordertmp",array("origintotle"=>$origintotle,"goods_amount"=>$orderask,"pay_fee"=>$pay_fee,"platform_fee"=>$platform_fee),"id=".$orderID);
				}
				//更新日志
				
				
				$this->db2->update("db_amzordertmp",array("flag"=>2,"descr"=>'已同步系统成功'),"tradeid='".$rs["tradeid"]."' AND id ='".$rs["id"]."'");

				if ($this->db1->trans_status() === FALSE)
				{
					$this->db1->trans_rollback();
				}
				else
				{
					$this->db1->trans_commit();
				}


		
			
			return $this->getinsertorderlist();
	}
	/****************读取抓取到的退款信息**********************/
	public function amzorder_fba_refundlist()
	{
		$this->db2->limit(1);
		$row = $this->db2->get_where("db_fba_refundlist","is_status=1 ")->result_array();
		if(count($row)==0)
		{
			return false;
		}
		$rs = $row[0];
		
		$rorder = $this->db1->get_where("db_amzordertmp_refund","fba_refundlist_id='".$rs["id"]."'")->result_array();
		if($rorder[0]["id"])
		{
			$this->db2->update("db_fba_refundlist",array("is_status"=>2),"id='".$rs["id"]."' ");
			return $this->amzorder_fba_refundlist();
		}
		$postdata="";
		$amazonOrder = $this->db1->get_where("db_amzordertmp","tradeid='".$rs["amazon_id"]."'")->result_array();
		if($amazonOrder[0]["id"])
		{
			$amazon_id = $amazonOrder[0]["id"];
		}else{
			$amazon_id = 0;
		}
		$rowcost = $this->db2->get_where("db_fba_cost"," amazon_id = '".$rs["amazon_id"]."'")->result_array();	//读取FBA的费用

		//SKU需要替换成正常的
		$goods =  $this->db1->get_where("db_amzordertmpsell","ordertmpid='".$amazon_id."' AND oldgoodsku = '".$rs['sku']."' ")->result_array();
		if($goods[0]['productid'])
		{
			$sku = $goods[0]['productid'];
			$sku_id = $goods[0]['goods_id'];
		}else{
			$oldgoodsku = trim($rs['sku']);
			$oldgoodsku = str_replace("-FBA","",$oldgoodsku);
			$oldgoodsku = str_replace("-fba","",$oldgoodsku);
			$oldgoodsku = str_replace("FBA-","",$oldgoodsku);
			$oldgoodsku = str_replace("FBA","",$oldgoodsku);
			/*****************替换SKU方式********
				**  1、是否存在123.fshop数据库d_aotocreatesku表中
				**  2、是否存在在商品的db_goods 中的cognatelist字段
				**  3、是否db_salesku中
			*********************************/
			$sku = "";
			$newgoods = $this->db2->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopname='".$rs["shopname"]."' ")->result_array();
			if(count($newgoods)>0)
			{
				$sku = $newgoods[0]["parentsku"];
				$sku_id =0;
			}else{
				$newgoods = $this->db1->get_where("db_goods","goods_sku='".$oldgoodsku."' or cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
				if(count($newgoods)>0)
				{
					$sku = $newgoods[0]["goods_sku"];
					$sku_id = $newgoods[0]['goods_id'];
				}else{
					$newgoods = $this->db1->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();
					if(count($newgoods)>0)
					{
						$sku = $newgoods[0]["goods_sku"];
						$sku_id = $newgoods[0]['goods_id'];
					}
				
				}
			}

			if(!$sku)
			{
				$sku = $oldgoodsku;
				$sku_id = 0;
			}
		}

		
	
		$costprice = $this->CI->fun->get_Goods_costprice($sku);
		$refundMoney = $rowcost[0]['refundMoney'];
		$postdata['refund_time'] = $rs['refund_time'];
		$postdata['amazon_id'] = $amazon_id;
		$postdata['tradeid'] = $rs['amazon_id'];
		$postdata['sku']	 = $sku;
		$postdata['goods_id']	 = $sku_id;
		$postdata['quantity'] = $rs['quantity'];
		$postdata['status'] = $rs['status'];
		$postdata['costprice'] = $costprice?$costprice:0;
		$postdata['customer_comments'] = $rs['customer_comments'];
		$postdata['shopid'] = $rs['shopid'];
		$postdata['shopname'] = $rs['shopname'];
		$postdata['fba_refundlist_id'] = $rs['id'];
		$this->db1->trans_begin();	//事务开始
		$this->db1->insert("db_amzordertmp_refund",$postdata);
		$orderID = $this->db1->insert_id();
		
		$this->db2->update("db_fba_refundlist",array("is_status"=>2),"id='".$rs["id"]."'");
		$this->db1->update("db_amzordertmp",array("refundMoney"=>$refundMoney,"status"=>3),"tradeid='".$rs["amazon_id"]."'");
		if ($this->db1->trans_status() === FALSE)
		{
			$this->db1->trans_rollback();
		}
		else
		{
			$this->db1->trans_commit();
		}
		return $this->amzorder_fba_refundlist();
	}

	/*************************抓取FBA库存表******************************/
	public function getFBAstock()
	{
		$times = date("Y-m-d",strtotime("-2 day"));
		$startime = $times." 00:00:00";
		$endtime  = date("Y-m-d")." 23:59:59";
	
		$this->db1->query("TRUNCATE db_fba_stock");
		$this->db1->update("db_goods_stock",array("stock"=>0),"storage_id = 9");//清除所有亚马逊库存
		$row = $this->db2->group_by('asin')->get_where("db_fba_stock","  Warehouse_code='SELLABLE' AND Quantity>0 AND instime >='".strtotime($startime)."' AND instime <='".strtotime($endtime)."'")->result_array();
		$post="";
		$i=0;
		$s =0;
		foreach($row as $keyst=>$rs)
		{
		
			$oldgoodsku = $rs["sku"];
			if(strpos($oldgoodsku,"@") === false){  
				$oldgoodsku = $rs["sku"];
			}else{
				$oldgoodsku = explode("@",$rs["sku"]);
				$oldgoodsku = $oldgoodsku[0];
			}

			$oldgoodsku = str_replace("-FBA","",$oldgoodsku);
			$oldgoodsku = str_replace("-fba","",$oldgoodsku);
			$oldgoodsku = str_replace("FBA-","",$oldgoodsku);
			$oldgoodsku = str_replace("FBA","",$oldgoodsku);
			$oldgoodsku = trim($oldgoodsku);

	
		
			/*****************替换SKU方式********
				**  1、是否存在123.fshop数据库d_aotocreatesku表中
				**  2、是否存在在商品的db_goods 中的cognatelist字段
				**  3、是否db_salesku中
			*********************************/
			$sku = "";
			$newgoods = $this->db2->select('parentsku')->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopname='".$rs['shopname']."' ")->result_array();
			if(count($newgoods)>0)
			{
				$sku = $newgoods[0]["parentsku"];
				$newgoods = $this->db1->select('goods_sku,goods_id')->get_where("db_goods","goods_sku='".$sku."' or cognatelist like '%,".$sku.",%'")->result_array(); 
				$sku_id = $newgoods[0]['goods_id']?$newgoods[0]['goods_id']:0;
			}else{
				$newgoods = $this->db1->select('goods_sku,goods_id')->get_where("db_goods","goods_sku='".$oldgoodsku."' or cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
				if(count($newgoods)>0)
				{
					$sku = $newgoods[0]["goods_sku"];
					$sku_id = $newgoods[0]['goods_id'];
				}else{
					$newgoods = $this->db1->select('goods_sku,goods_id')->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();
					if(count($newgoods)>0)
					{
						$sku = $newgoods[0]["goods_sku"];
						$sku_id = $newgoods[0]['goods_id'];
					}
				
				}
			}

			if(!$sku)
			{
				$sku = $oldgoodsku;
				$sku_id = 0;
			}
			$costprice = $this->CI->fun->get_Goods_costprice($sku);
			
			$post[$keyst]['sku'] =$sku;
			$post[$keyst]['goods_id'] =$sku_id;
			$post[$keyst]['costprice'] = $costprice;
			$post[$keyst]['fulfillment_sku'] =$rs["fulfillment_sku"];
			$post[$keyst]['asin'] =$rs["asin"];
			$post[$keyst]['Warehouse_code'] = $rs['Warehouse_code'];
			$post[$keyst]['Quantity'] = $rs['Quantity'];
			$post[$keyst]['shopid'] = $rs['shopid'];
			$post[$keyst]['shopname'] = $rs['shopname'];
			$post[$keyst]['instime'] = $rs['instime'];


			//存数据到亚马逊仓库
			
			//清除所有亚马逊库存
			/*
			if($sku_id>0)
			{
				//需要判断库存表相关信息
				$rs_stock = $this->CI->fun->getdatabasesdetail('db_goods_stock'," AND goods_id = '".$sku_id."' AND storage_id = 9");
				if($rs_stock){
					//$this->db1->update("db_goods_stock",array("stock"=>$rs['Quantity']),"id=". $rs_stock['id']);
					$upstock[$i]["stock"] = $rs['Quantity']+$rs_stock["stock"];
					$upstock[$i]["id"] = $rs_stock['id'];
					$i=$i+1;
				}else{
					$insertstock[$s]['goods_id'] = $sku_id;
					$insertstock[$s]['storage_id'] = 9;
					$insertstock[$s]['storage_name'] = '亚马逊';
					$insertstock[$s]['stock'] = $rs['Quantity'];
					$s = $s+1;
				}
			}*/
			
			
		}
		$this->db1->insert_batch('db_fba_stock', $post);//批量更新
		
		$query = $this->db1->query("SELECT sum(Quantity) as sumq ,goods_id FROM `db_fba_stock` WHERE 1 and goods_id >0 and Warehouse_code='SELLABLE' GROUP by goods_id");
        $stocklist = $query->result_array();
		if(count($stocklist)>0)
		{
			foreach($stocklist as $key=>$rs)
			{
				$sku_id = $rs["goods_id"];
				$rs_stock = $this->CI->fun->getdatabasesdetail('db_goods_stock'," AND goods_id = '".$sku_id."' AND storage_id = 9");
				if($rs_stock){
					$upstock[$i]["stock"] = $rs['sumq']+$rs_stock["stock"];
					$upstock[$i]["id"] = $rs_stock['id'];
					$i=$i+1;
				}else{
					$insertstock[$s]['goods_id'] = $sku_id;
					$insertstock[$s]['storage_id'] = 9;
					$insertstock[$s]['storage_name'] = '亚马逊';
					$insertstock[$s]['stock'] = $rs['sumq'];
					$s = $s+1;
				}
			}
		}

		if(count($upstock)>0)
		{
			$this->db1->update_batch('db_goods_stock', $upstock,"id");//批量更新
		}
		if(count($insertstock)>0)
		{
			$this->db1->insert_batch('db_goods_stock', $insertstock);//批量更新
		}



		
		return false;
	}


	/*************************读取亚马逊物流已收到库存报告******************************/
	public function getFBAfulflllment()
	{
		
		$row = $this->db2->get_where("db_fba_fulflllment"," is_update = 0")->result_array();
		$post="";
		$i=0;
		$s =0;
		$isu =0;
		foreach($row as $keyst=>$rs)
		{
		
			$oldgoodsku = $rs["sku"];
			if(strpos($oldgoodsku,"@") === false){  
				$oldgoodsku = $rs["sku"];
			}else{
				$oldgoodsku = explode("@",$rs["sku"]);
				$oldgoodsku = $oldgoodsku[0];
			}

			$oldgoodsku = str_replace("-FBA","",$oldgoodsku);
			$oldgoodsku = str_replace("-fba","",$oldgoodsku);
			$oldgoodsku = str_replace("FBA-","",$oldgoodsku);
			$oldgoodsku = str_replace("FBA","",$oldgoodsku);
			$oldgoodsku = trim($oldgoodsku);

	
		
			/*****************替换SKU方式********
				**  1、是否存在123.fshop数据库d_aotocreatesku表中
				**  2、是否存在在商品的db_goods 中的cognatelist字段
				**  3、是否db_salesku中
			*********************************/
			$sku = "";
			$newgoods = $this->db2->select('parentsku')->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopname='".$rs['shopname']."' ")->result_array();
			if(count($newgoods)>0)
			{
				$sku = $newgoods[0]["parentsku"];
				$newgoods = $this->db1->select('goods_sku,goods_id')->get_where("db_goods","goods_sku='".$sku."' or cognatelist like '%,".$sku.",%'")->result_array(); 
				$sku_id = $newgoods[0]['goods_id']?$newgoods[0]['goods_id']:0;
			}else{
				$newgoods = $this->db1->select('goods_sku,goods_id')->get_where("db_goods","goods_sku='".$oldgoodsku."' or cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
				if(count($newgoods)>0)
				{
					$sku = $newgoods[0]["goods_sku"];
					$sku_id = $newgoods[0]['goods_id'];
				}else{
					$newgoods = $this->db1->select('goods_sku,goods_id')->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();
					if(count($newgoods)>0)
					{
						$sku = $newgoods[0]["goods_sku"];
						$sku_id = $newgoods[0]['goods_id'];
					}
				
				}
			}

			if(!$sku)
			{
				$sku = $oldgoodsku;
				$sku_id = 0;
			}
			$costprice = $this->CI->fun->get_Goods_costprice($sku);
			
			$post[$keyst]['sku'] =$sku;
			$post[$keyst]['goods_id'] =$sku_id;
			$post[$keyst]['fulflllment_data'] = $rs['fulflllment_data'];
			$post[$keyst]['fnsku'] =$rs["fnsku"];
			$post[$keyst]['fulfillment_center_id'] =$rs["fulfillment_center_id"];
			$post[$keyst]['shipment_id'] = $rs['shipment_id'];
			$post[$keyst]['quantity'] = $rs['quantity'];
			$post[$keyst]['shopid'] = $rs['shopid'];
			$post[$keyst]['goods_name'] = addslashes($rs['goods_name']);
			$post[$keyst]['shopname'] = $rs['shopname'];
			$post[$keyst]['instime'] = $rs['instime'];

			$this->db2->update("db_fba_fulflllment",array("is_update"=>1),"id='".$rs["id"]."'");
			
			$isu = 1;				
		}
		if($isu==1)$this->db1->insert_batch('db_fba_fulflllment', $post);//批量更新
		
		
		return false;
	}

	//读取亚马逊销售平台的所有SKU列表
	public function getgoodslist()
	{
		
		$shopData = $this->db2->select("GROUP_CONCAT(DISTINCT(shopid)) as shopid")->get("db_amazon_goodslist")->result_array();
		if($shopData[0]['shopid'])
		{
			$shopid = explode(",",$shopData[0]['shopid']);
			foreach($shopid as $key=>$rsshop)
			{
				$shopmoney = $this->CI->fun->getdatabasesdetail("db_order_list"," AND shopid = '".$rsshop."'","moneyrate,moneytype,shopid ","order by order_id DESC LIMIT 0,1");
				$newarray[$rsshop] = $shopmoney;

				$link = $this->CI->fun->getdatabasesdetail("d_shop"," AND id = '".$rsshop."'","amazonkey");
				$amazonkey = unserialize($link["amazonkey"]);
				$serverurl = $amazonkey["serverurl"];
				$serverurl = str_replace("mws.amazonservices","www.amazon",$serverurl);
				$newarray[$rsshop]["url"] = $serverurl."/dp/";
			}
		}
		
		$row = $this->db2->get_where("db_amazon_goodslist"," is_update=0 AND fulfillment_channel='DEFAULT'")->result_array();
		if(count($row)==0)
		{
			return false;
		}
		$post = "";
		foreach($row as $keyst=>$rs)
		{
			$detail = $this->CI->fun->getdatabasesdetail("db_amazon_productlist"," and sales_sku ='".$rs['goods_sku']."' AND shopid = '".$rs['shopid']."'","id"); //如果店铺中的平台销售SKU存在！删除原来的，更新最新的一条
			if($detail["id"])
			{
				$this->db1->delete('db_amazon_productlist',"id='".$detail['id']."'");
			}


			$post[$keyst]['types'] =0;
			$post[$keyst]['platform_id'] =2;
			$post[$keyst]['shopid'] =$rs["shopid"];
			$post[$keyst]['shopname'] =$rs["shopname"];


			$oldgoodsku = $rs["goods_sku"];
			
			if(strpos($oldgoodsku,"@") === false){  
				$oldgoodsku = $rs["goods_sku"];
			}else{
				$oldgoodsku = explode("@",$rs["goods_sku"]);
				if($this->CI->fun->getfactorygoodsku($oldgoodsku[0]))
				{
					$oldgoodsku = $rs["goods_sku"];
				}else{
					$oldgoodsku = $oldgoodsku[0];
				}
			}
			$oldgoodsku = str_replace("-DZ","",$oldgoodsku);
			$oldgoodsku = trim($oldgoodsku);

			/*****************替换SKU方式********
				**  1、是否存在123.fshop数据库d_aotocreatesku表中
				**  2、是否存在在商品的db_goods 中的cognatelist字段
				**  3、是否db_salesku中
			*********************************/
			$productid = "";
			$newgoods = $this->db2->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopname='".$rs["shopname"]."' ")->result_array();
			if(count($newgoods)>0)
			{
				$productid = $newgoods[0]["parentsku"];
			}else{
				$newgoods = $this->db1->get_where("db_goods","goods_sku='".$oldgoodsku."' or cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
				if(count($newgoods)>0)
				{
					$productid = $newgoods[0]["goods_sku"];
				}else{
					$newgoods = $this->db1->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();
					if(count($newgoods)>0)
					{
						$productid = $newgoods[0]["goods_sku"];
					}
				
				}
			}

			if(!$productid)
			{
				$productid = $oldgoodsku;
			}
			$parent_sku = "";
			$goods_id   = "";
			$goods_name = "";
			$rgoods = $this->db1->select('goods_parent_sku,goods_id,goods_name')->get_where("db_goods","goods_sku='".$productid."'")->result_array();
			if($rgoods[0]["goods_id"])
			{
				$parent_sku = $rgoods[0]["goods_parent_sku"];
				$goods_id = $rgoods[0]["goods_id"];
				$goods_name = $rgoods[0]["goods_name"];
			}
			$post[$keyst]['goods_id'] = $goods_id?$goods_id:0;
			$post[$keyst]['parent_sku'] = $parent_sku;
			$post[$keyst]['goods_sku'] = $productid;
			$post[$keyst]['goods_name'] = $rs['goods_name'];
			$post[$keyst]['sales_sku'] = $rs['goods_sku'];
			$post[$keyst]['moneytype'] = $newarray[$rs['shopid']]['moneytype'];
			$post[$keyst]['moneyrate'] =  $newarray[$rs['shopid']]['moneyrate'];
			$post[$keyst]['original_price'] = $rs['price'];
			$post[$keyst]['price'] = round( $newarray[$rs['shopid']]['moneyrate'] * $rs["price"] ,2);
			$post[$keyst]['qty'] = $rs['qty'];
			$post[$keyst]['sales_time'] = $rs['opendate'];
			$post[$keyst]['product_id'] = $rs['asin'];
			$post[$keyst]['product_link'] =  $newarray[$rs['shopid']]['url'].$rs['asin'];
			$post[$keyst]['instime'] = time();

			$this->db2->update("db_amazon_goodslist",array("is_update"=>1),"id ='".$rs["id"]."'");
		}

		$this->db1->insert_batch('db_amazon_productlist', $post);//批量更新
	}

	//读取亚马逊消单
	public function amazonordercancel()
	{
		$row = $this->db2->get_where("db_amz_report_myship_refund"," is_status=0")->result_array();
		$post="";
		if(count($row)==0)
		{
			return false;
		}

		//先计算汇率
		$shopData = $this->db2->select("GROUP_CONCAT(DISTINCT(shopid)) as shopid")->get("db_amz_report_type_list")->result_array();
		if($shopData[0]['shopid'])
		{
			$shopid = explode(",",$shopData[0]['shopid']);
			foreach($shopid as $key=>$rsshop)
			{
				$shopmoney = $this->CI->fun->getdatabasesdetail("db_order_list"," AND shopid = '".$rsshop."'","moneyrate,moneytype,shopid ","order by order_id DESC LIMIT 0,1");
				$newarray[$rsshop] = $shopmoney;
			}
		}
		foreach($row as $keyst=>$rs)
		{
			$post[$keyst]['shopid'] =$rs['shopid'];
			$post[$keyst]['shopname'] =$rs['shopname'];
			$post[$keyst]['tradeid'] =$rs["tradeid"];
			$post[$keyst]['Principal'] =$rs["Principal"];
			$post[$keyst]['Commission'] = $rs['Commission'];
			$post[$keyst]['RefundCommission'] = $rs['RefundCommission'];
			$post[$keyst]['report_time'] = $rs['report_time'];
			$post[$keyst]['report_id'] = $rs['report_id'];
			$post[$keyst]['goods_sku'] =",". $rs['goods_sku'].",";
			$post[$keyst]['instime'] = $rs['instime'];
			
			 
			//汇率
			$post[$keyst]['moneyrate'] =  $newarray[$rs['shopid']]['moneyrate'];
			$post[$keyst]['moneytype'] =  $newarray[$rs['shopid']]['moneytype'];
			//退款人民币
			$post[$keyst]['RMBmoney'] = round( $newarray[$rs['shopid']]['moneyrate'] * $rs["Principal"] ,2);
			//退款费用
			$post[$keyst]['RMBrefundmoney'] = round( $newarray[$rs['shopid']]['moneyrate'] * $rs["RefundCommission"] ,2);

			//订单信息
			$Order = $this->CI->fun->getdatabasesdetail("db_order_list"," AND tradeid = '".$rs['tradeid']."'","order_status,shipping_status,country_cn,shipping_originask,add_time,ordertime");
			if($Order)
			{
				$post[$keyst]['order_status'] = $Order['order_status'];
				$post[$keyst]['order_id'] = $Order['order_id'];
				$post[$keyst]['shipping_status'] = $Order['shipping_status'];
				$post[$keyst]['country_cn'] = $Order['country_cn'];
				if( $Order['shipping_originask']>0)
				{
					$post[$keyst]['shipping_fee'] ="-".round( $Order['shipping_originask'] * $newarray[$rs['shopid']]['moneyrate'] ,2);
				}else{
					$post[$keyst]['shipping_fee'] =0;
				}
				$post[$keyst]['add_time'] = $Order['add_time'];
				$post[$keyst]['ordertime'] = $Order['ordertime'];
				$post[$keyst]['shipping_originask'] = $Order['shipping_originask'];
				$post[$keyst]['isform'] = 0;
				$post[$keyst]['mabangorder'] ='';
			}else{

				$this->CI->load->library('Mabang');
				$res= $this->CI->mabang->getorderdata($rs['tradeid'],'ORIGINEXPRESSMONEY,CUSTOMERRESERVE2,ORDERTIME,ORDERID');
				
				if($res){
					if( $res['ORIGINEXPRESSMONEY']>0)
					{
						$post[$keyst]['shipping_fee'] ="-".round( $res['ORIGINEXPRESSMONEY'] * $newarray[$rs['shopid']]['moneyrate'] ,2);
					}else{
						$post[$keyst]['shipping_fee'] =0;
					}
					$post[$keyst]['order_status'] =5;
					$post[$keyst]['order_id'] = 0;
					$post[$keyst]['shipping_status'] = 1;
					$post[$keyst]['country_cn'] = $res['CUSTOMERRESERVE2'];
					$post[$keyst]['add_time'] =strtotime($res['ORDERTIME']);
					$post[$keyst]['ordertime'] =date("Y-m-d H:i:s",strtotime($res['ORDERTIME']));
					$post[$keyst]['shipping_originask'] = $res['ORIGINEXPRESSMONEY'];
					$post[$keyst]['mabangorder'] = $res['ORDERID'];
					$post[$keyst]['isform'] = 1;
				}else{
					$post[$keyst]['order_status'] = 5;
					$post[$keyst]['shipping_status'] = 1;
					$post[$keyst]['country_cn'] = '';
					$post[$keyst]['shipping_fee'] =0;
					$post[$keyst]['add_time'] = '';
					$post[$keyst]['ordertime'] = '';
					$post[$keyst]['shipping_originask'] =0;
					$post[$keyst]['isform'] = 3;
					$post[$keyst]['mabangorder'] ='';
					$post[$keyst]['order_id'] = 0;
				}
			}
			
			
			$this->db2->update("db_amz_report_myship_refund",array("is_status"=>1),"id ='".$rs["id"]."'");
		}
		
		$this->db1->insert_batch('db_amzordertmp_cancel', $post);//批量更新
	}

	/****************读取马帮抓取FBA的订单到新系统**********************/
	public function getMabanginsertFBAorderlist()
	{
		return; //不再读取 2017.11.27
		$factorycode = $this->factorycode();
		
		$this->db2->limit(1);
		$row = $this->db2->get_where("fshop.db_sysorder"," flag=0 AND ordersource = 'AFN' AND synflag >1")->result_array();
		
		if(count($row)==0)
		{
			return false;
		}
		$rs = $row[0];
	
			$rorder = $this->db1->get_where("db_amzordertmp","tradeid='".$rs["tradeid"]."'")->result_array();
			if($rorder[0]["id"])
			{
				$this->db2->update("fshop.db_sysorder",array("flag"=>1),"tradeid='".$rs["tradeid"]."'  AND shopid='".$rs["shopid"]."' ");
				
				return $this->getMabanginsertFBAorderlist();
			}
			
			$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["moneytype"]."'")->result_array();
			$exchangerate=$exchange[0]["rate"]; //汇率
			$postdata="";
			$postdata["groupid"] =  $this->getNo('amazon',$rs["tradeid"],$rs["shopid"]);
			$dates = date("Y-m-d",strtotime($rs['downtime']));
			$postdata["dates"] = $dates;
			$rsdb = $this->db2->get_where("fshop.db_amzordertmp","amzorderid='".$rs["oringorderid"]."'")->result_array();


			$postdata["custid"] =addslashes(trim($rsdb[0]["custid"]));
			$postdata["custname"] =addslashes(trim($rsdb[0]["custname"]));
			$postdata["custcountry"] = $rsdb[0]["custcountry"];


			$rscountry = $this->db1->get_where("d_chinaexpress","NAME='".$rsdb[0]["custcountry"]."'")->result_array();
			if($rscountry[0]["id"]){
				$postdata["country_cn"] = $rscountry[0]["FILED1"];
			}
			if($rsdb[0]["countrycode"]=="")
			{
				$rscountry = $this->db1->get_where("d_country","countrynamecn='".trim($rsdb[0]["custcountry"])."'")->result_array();
				$country_code = $rscountry[0]['countryid'];
			}else{
				$country_code =  $rsdb[0]["countrycode"];
			}
			$postdata["countrycode"] = $country_code;
			
			



			if($rsdb[0]["shopname"]=="yuanyuan"){
				$rsdb[0]["shopname"] = "YUAN YUAN";
			}
			if($rsdb[0]["shopname"]=="JP11"){
				$rsdb[0]["shopname"] = "JP-coshans";
			}

			

			$postdata["custprovince"] = $rsdb[0]["custprovince"];
			$postdata["custcity"] = $rsdb[0]["custcity"];
			$postdata["custaddress1"] = addslashes(trim($rsdb[0]["custaddress1"]));
			$postdata["custaddress2"] = addslashes(trim($rsdb[0]["custaddress2"]));
			$postdata["custzipcode"] = $rsdb[0]["custzipcode"]?$rsdb[0]["custzipcode"]:0;
			$postdata["custtel1"] = $rsdb[0]["custtel1"]?$rsdb[0]["custtel1"]:0;
			$postdata["custtel2"] = $rsdb[0]["custtel2"];
			$postdata["custemail"] = $rsdb[0]["custemail"];
			

			$rshop = $this->db1->get_where("d_shop","name='".$rsdb[0]["shopname"]."'")->result_array();
		
			$postdata["shopname"] = $rshop[0]["name"];
			$postdata["shopid"] = $rshop[0]["id"];
			$postdata["moneytype"] = $rs["moneytype"];
			$postdata["tradeid"] = $rs["tradeid"];
			$postdata["fulfillmentchannel"] = 'AFN';
			$postdata["status"] = 1;
			$postdata["origintotle"] = $rs["originask"]+$rs["originexpressask"];	//原金额这个金额包含运费
			$exchange=$this->db1->get_where("d_moneyrate","name='".$rs["moneytype"]."'")->result_array();
			$exchangerate=$exchange[0]["rate"]; 
			$orderask = ($rs["originask"]+$rs["originexpressask"]) * $exchangerate;
			$postdata["goods_amount"] =$orderask;
			$postdata["shipping_fee"] = $rs["originexpressask"]* $exchangerate;
			$postdata["originexpressask"] = $rs["originexpressask"];
			$postdata["instime"] = strtotime($rs['downtime']);
			$postdata["ordercreatetime"] = $rs["ordertime"];
			$postdata["saleschannel"] = $rs["saleschannel"];
			$postdata["pay_fee"] = $orderask*0.015;
			$postdata["platform_fee"] = $orderask*0.15;
			$postdata["isform"] = 1;
			$postdata['moneyrate']  = $exchangerate;//汇率
			
			

		
				$this->db1->trans_begin();	//事务开始
			
				$this->db1->insert("db_amzordertmp",$postdata);
				$orderID = $this->db1->insert_id();
				
				



				$sell = $this->db2->get_where("fshop.db_amzordertmpsell","ordertmpid='".$rsdb[0]["id"]."'")->result_array();
				
				$weight = 0;
				$allshipprice=0;
				$origintotle = 0;
				foreach($sell as $key=>$res)
				{
					
					

					$allshipprice =$allshipprice+$res['shipprice']-$res['codfeediscount'];	//运费
					$origintotle = $origintotle+$res['sellprice']*$res["ordernum"];	//商品金额
					$oldgoodsku = $res["productid"];
					if(strpos($oldgoodsku,"@") === false){  
						$oldgoodsku = $res["productid"];
					}else{
						$oldgoodsku = explode("@",$res["productid"]);
						$oldgoodsku = $oldgoodsku[0];
					}
					
						$oldgoodsku = str_replace("-FBA","",$oldgoodsku);
						$oldgoodsku = str_replace("-fba","",$oldgoodsku);
						$oldgoodsku = str_replace("FBA-","",$oldgoodsku);
						$oldgoodsku = str_replace("FBA","",$oldgoodsku);
						$oldgoodsku = trim($oldgoodsku);
					/*****************替换SKU方式********
						**  1、是否存在123.fshop数据库d_aotocreatesku表中
						**  2、是否存在在商品的db_goods 中的cognatelist字段
						**  3、是否db_salesku中
					*********************************/
					$productid = "";
					$newgoods = $this->db2->get_where("fshop.d_aotocreatesku","autosku='".$oldgoodsku."' AND shopname='".$rshop[0]["name"]."' ")->result_array();
					if(count($newgoods)>0)
					{
						$productid = $newgoods[0]["parentsku"];
					}else{
						$newgoods = $this->db1->get_where("db_goods","goods_sku='".$oldgoodsku."' or cognatelist like '%,".$oldgoodsku.",%'")->result_array(); 
						if(count($newgoods)>0)
						{
							$productid = $newgoods[0]["goods_sku"];
						}else{
							$newgoods = $this->db1->get_where("db_salesku","autosku='".$oldgoodsku."'")->result_array();
							if(count($newgoods)>0)
							{
								$productid = $newgoods[0]["goods_sku"];
							}
						
						}
					}

					if(!$productid)
					{
						$productid = $oldgoodsku;
					}

					





					$rgoods = $this->db1->get_where("db_goods","goods_sku='".$productid."'")->result_array();
					if($rgoods[0]["goods_id"])
					{
						$goods_id = $rgoods[0]["goods_id"];
						$sweight = $res["ordernum"] * $rgoods[0]["g_weight"];
						$weight = $weight+$sweight;
						$goods_name =  $rgoods[0]["goods_name"];
						/*****************成本价计算方式********
						**  11、12开头定制的衣服按成本价计算
						**  批量的sku 按关联价计算
						**  外采购的衣服按成本价计算
						*********************************/
						$costprice = 0;
						if(is_numeric($productid) && preg_match('|^\d{8}$|',$productid))	//数字并且8位SKU并且11 12开头
						{
							$goodscode  = substr($productid,0,2);//取开头2位数
							if(in_array($goodscode,$factorycode))	//是否存在在工厂code
							{
								$costprice = $rgoods[0]["g_costprice"];	//定制衣服按成本价计算
							}
						}else{
							//如果当前SKU不是8位，查询父SKU是不是8位并且11，12开头
							if(is_numeric($rgoods[0]["goods_parent_sku"]) && preg_match('|^\d{8}$|',$rgoods[0]["goods_parent_sku"]))	//数字并且8位SKU并且11 12开头
							{
								$goodscodes  = substr($rgoods[0]["goods_parent_sku"],0,2);//取开头2位数
								if(in_array($goodscodes,$factorycode))	//是否存在在工厂code
								{
									$costprice = $rgoods[0]["bulkprice"];	//批量按关联价计算
								}
							}else{
								$costprice = $rgoods[0]["g_costprice"];
							}
							
						}
						
					}else{
						$goods_id = 0 ;
						$costprice = 0;
						$goods_name="";
					}

					$amount = $res["ordernum"] * $res["sellprice"];
					$postsell = "";
					$postsell["ordertmpid"] = $orderID;
					$postsell["productname"] = $goods_name?$goods_name:addslashes($res["productname"]);
					$postsell["productid"] = $productid;
					$postsell["goods_id"] = $goods_id;
					$postsell["costprice"] = $costprice*$res["ordernum"];
					$postsell["ordernum"] = $res["ordernum"];
					$postsell["sellprice"] = $res["sellprice"]*$exchangerate;
					$postsell["goods_weight"] = $rgoods[0]["g_weight"]?$rgoods[0]["g_weight"]:0;
					$postsell["goods_amount"] = $amount*$exchangerate;
					$postsell["originsellprice"] = $res["sellprice"];
					$postsell["oldgoodsku"] = $oldgoodsku;

					$postsell["transactionid"] =$res["transactionid"];
					$postsell["codefee"] =$res["codefee"];;
					$postsell["codfeediscount"] =$res["codfeediscount"];
					$postsell["amount"] =$res["amount"];
					$postsell["asin"] =0;
					$postsell["promotionDiscount"] =0;
					//当前头程费用
					$derprice = $this->CI->fun->getdatabasesdetail("t_overseaproduct"," AND sku = '".$productid."'","deliverprice");
					if($derprice['deliverprice']>0){
						$postsell["deliverprice"] =$derprice['deliverprice'];
					}

				
					$this->db1->insert("db_amzordertmpsell",$postsell);
					
					if($goods_id==0)
					{
						$this->db1->update("db_amzordertmp",array("status"=>2),"id=".$orderID);
					}
					
				}
				
				/*  马帮中的这块暂时没有，以后再添加
				$rowcost = $this->db2->get_where("db_fba_cost"," amazon_id = '".$rs["tradeid"]."'")->result_array();	//读取FBA的费用
				if(count($rowcost)>0)
				{
					$rowcose = $rowcost[0];
					if($rowcose['refund']==0)	//没有退货
					{
						$fees = $rowcose['FBAPerOrderFulfillmentFee'] + $rowcose['FBAPerUnitFulfillmentFee'] + $rowcose['FBAWeightBasedFee'] + $rowcose['Commission'] + $rowcose['FixedClosingFee'] + $rowcose['GiftwrapChargeback'] + $rowcose['SalesTaxCollectionFee'] + $rowcose['ShippingChargeback'] + $rowcose['VariableClosingFee'];
					}else{
						$fees = 0-($rs['origintotle']+ abs($rowcose['FBAPerUnitFulfillmentFee']));
					}
					$payship_fee = $fees *$exchangerate;
					$this->db1->update("db_amzordertmp",array("payship_fee"=>$payship_fee),"id=".$orderID);
				}
				*/
				if($allshipprice)
				{
					$shipping_fee =round($allshipprice * $exchangerate,2);
					$this->db1->update("db_amzordertmp",array("originexpressask"=>$allshipprice,"shipping_fee"=>$shipping_fee),"id=".$orderID);
				}
				if($origintotle)
				{
					$orderask = round($origintotle * $exchangerate,2);
					$pay_fee = round($orderask*0.015,2);
					$platform_fee = round($orderask*0.15,2);
					$this->db1->update("db_amzordertmp",array("origintotle"=>$origintotle,"goods_amount"=>$orderask,"pay_fee"=>$pay_fee,"platform_fee"=>$platform_fee),"id=".$orderID);
				}
				//更新日志
				
				$this->db2->update("fshop.db_sysorder",array("flag"=>1),"tradeid='".$rs["tradeid"]."'  AND orderid ='".$rs["orderid"]."'");
				

				if ($this->db1->trans_status() === FALSE)
				{
					$this->db1->trans_rollback();
				}
				else
				{
					$this->db1->trans_commit();
				}


		
			
			return $this->getMabanginsertFBAorderlist();
		
	}

	public  function getNo($shopName='',$tradeid='',$shopid='') {
		
		if($shopName)
		{
			if($shopName =='wish')
			{
				 $randCode = $this->randCode(5,1);
				 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
			}
			if($shopName =='amazon')
			{
				if($tradeid)
				{
					$no = str_replace("-","",$tradeid);
					$ors = $shopid.$no;
				}else{
					 $randCode = $this->randCode(5,1);
					 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
				}
			}
			if($shopName =='ebay')
			{
				if($tradeid)
				{
					$no = str_replace("-","",$tradeid);
					$ors = $no;
					}else{
					 $randCode = $this->randCode(5,1);
					 $ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
				}
			}
		
		}else{
			$randCode = $this->randCode(5,1);
			$ors=$randCode.substr(time(),-5).substr(microtime(),2,5);     //生成16位数字基本号
			/*
			$zigui = "FM";
			$sql = "select max(right( order_sn, 12 ) *1) as hot from db_order_list where dates='" . date("Y-m-d") . "' group by dates ";
			$query = $this->db1->query($sql);
			$hot = $query->result_array();
			if ($hot[0]['hot']) {
				$no = substr($hot[0]['hot'], 8, strlen($hot[0]['hot']));
				$no = $no + 10001;
				$no = date("Ymd") . substr($no, 1, strlen($no));

				$ors =$zigui . $no;
			}
			else
				$ors =$zigui . date("Ymd") . "0001";*/
		}
		$order  = $this->db1->get_where("db_order_list","order_sn ='".$ors."'")->result_array();
		if(count($order)>0)	//如果存在，则自动生成一个无序订单号
		{
			return $this->getNo();
		}else{
			return $ors;
		}

    }
	
	/**
	  +----------------------------------------------------------
	 * 生成随机字符串
	  +----------------------------------------------------------
	 * @param int       $length  要生成的随机字符串长度
	 * @param string    $type    随机码类型：0，数字+大小写字母；1，数字；2，小写字母；3，大写字母；4，特殊字符；-1，数字+大小写字母+特殊字符
	  +----------------------------------------------------------
	 * @return string
	  +----------------------------------------------------------
	 */
	function randCode($length, $type = 0) {
		if($length ==999)
		{
			$length=mt_rand(3,10);
		}
		$arr = array(1 => "123456789", 2 => "abcdefghijklmnopqrstuvwxyz", 3 => "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
		if ($type == 0) {
			array_pop($arr);
			$string = implode("", $arr);
		} elseif ($type == "-1") {
			$string = implode("", $arr);
		} else {
			$string = $arr[$type];
		}
		$count = strlen($string) - 1;
		$code = '';
		for ($i = 0; $i < $length; $i++) {
			$code .= $string[rand(0, $count)];
		}
		return $code;
	}


	public function factorycode()
	{
		$rsdb = $this->db1->get_where("db_factory","code >0")->result_array();
		foreach($rsdb as $key =>$rs)
		{
			$factorycode[] = $rs["code"];	//工厂编号
		}

		return $factorycode;
	}

	
	
}